/* eslint-disable no-unused-vars */
import './css/index.css';
let images = document.querySelectorAll('img');
let next = document.querySelector('.next');
let pre = document.querySelector('.pre');
let dotBox = document.querySelector('.dot-group');
let dot = dotBox.querySelectorAll('.dot');
let num = 0;
let dotNum = 0;

// 下一张轮播图点击事件
next.addEventListener('click', () => {
  num -= 600;
  dotNum++;
  images.forEach((el, index) => {
    if (num === -2400) {
      num = 0;
      el.style.transform = 'translateX(' + num + 'px)';
      dot[index].classList.remove('active-dot');
      dotNum = 0;
      dot[dotNum].classList.add('active-dot');
    } else {
      el.style.transform = 'translateX(' + num + 'px)';
      dot[index].classList.remove('active-dot');
      dot[dotNum].classList.add('active-dot');
    }
  });
});

// 上一张轮播图点击事件
pre.addEventListener('click', () => {
  num += 600;
  dotNum--;
  images.forEach((el, index) => {
    if (num === 600) {
      num = -1800;
      el.style.transform = 'translateX(' + num + 'px)';
      dot[index].classList.remove('active-dot');
      dotNum = 3;
      dot[dotNum].classList.add('active-dot');
    } else {
      el.style.transform = 'translateX(' + num + 'px)';
      dot[index].classList.remove('active-dot');
      dot[dotNum].classList.add('active-dot');
    }
  });
});

// 小圆点点击事件
dotBox.addEventListener('click', (e) => {
  if (e.target.classList[0] == 'dot') {
    e.target.parentElement.childNodes.forEach((el) => {
      if (el.localName == 'div') el.classList.remove('active-dot');
    });

    e.target.classList.add('active-dot');
    let dotarr = [...dot];
    dotNum = dotarr.indexOf(e.target);
    switch (dotNum) {
      case 0:
        num = 0;
        images.forEach((el) => {
          el.style.transform = 'translateX(' + num + 'px)';
        });
        break;
      case 1:
        num = -600;
        images.forEach((el) => {
          el.style.transform = 'translateX(' + num + 'px)';
        });
        break;
      case 2:
        num = -1200;
        images.forEach((el) => {
          el.style.transform = 'translateX(' + num + 'px)';
        });
        break;
      case 3:
        num = -1800;
        images.forEach((el) => {
          el.style.transform = 'translateX(' + num + 'px)';
        });
        break;
      default:
        break;
    }
  }
});

// 定时器自动轮播
let timer = setInterval(() => {
  if (dotNum < 3) {
    dotNum++;
    num -= 600;
    images.forEach((el) => {
      el.style.transform = 'translateX(' + num + 'px)';
    });
    dot.forEach((el, index, arr) => {
      arr[index].classList.remove('active-dot');
      arr[dotNum].classList.add('active-dot');
    });
  } else {
    dotNum = 0;
    num = 0;
    images.forEach((el) => {
      el.style.transform = 'translateX(' + num + 'px)';
    });
  }
  dot.forEach((el, index, arr) => {
    arr[index].classList.remove('active-dot');
    arr[dotNum].classList.add('active-dot');
  });
}, 3000);
